/*
 * ModifierEditor.java
 *
 * Created on August 4, 2006, 12:03 AM
 */
package com.floreantpos.ui.model;

import com.floreantpos.main.Application;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;

import com.floreantpos.model.MenuModifier;
import com.floreantpos.model.MenuModifierGroup;
import com.floreantpos.model.Tax;
import com.floreantpos.model.dao.ModifierDAO;
import com.floreantpos.model.dao.ModifierGroupDAO;
import com.floreantpos.model.dao.TaxDAO;
import com.floreantpos.swing.FixedLengthDocument;
import com.floreantpos.swing.MessageDialog;
import com.floreantpos.ui.BeanEditor;
import com.floreantpos.util.POSUtil;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingConstants;

/**
 *
 * @author MShahriar
 */
public class MenuModifierForm extends BeanEditor {

  /**
   * Creates new form ModifierEditor
   */
  public MenuModifierForm() throws Exception {
    this(new MenuModifier());
  }

  public MenuModifierForm(MenuModifier modifier) throws Exception {
    initComponents();

    tfName.setDocument(new FixedLengthDocument(20));

    ModifierGroupDAO modifierGroupDAO = new ModifierGroupDAO();
    List<MenuModifierGroup> groups = modifierGroupDAO.findAll();
    cbModifierGroup.setModel(new DefaultComboBoxModel(new Vector<MenuModifierGroup>(groups)));

    TaxDAO taxDAO = new TaxDAO();
    tax = taxDAO.get(1);

    setBean(modifier);
  }

  private void initComponents() {

    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new com.floreantpos.swing.TransparentPanel();
    jLabel2 = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();
    tfPrice = new javax.swing.JFormattedTextField();
    tfStdCost = new javax.swing.JFormattedTextField();
    tfName = new javax.swing.JFormattedTextField();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    cbModifierGroup = new javax.swing.JComboBox();
    btnPrintToKitchen = new javax.swing.JCheckBox();
    btnPizzaModifier = new javax.swing.JCheckBox();

    jLabel2.setText(com.floreantpos.POSConstants.PRICE + ":");

    jLabel1.setText(com.floreantpos.POSConstants.NAME + ":");

    jLabel5.setText("Custo Std.:");

    tfPrice.setText("0,00");
    tfPrice.setHorizontalAlignment(SwingConstants.RIGHT);

    tfStdCost.setText("0,00");
    tfStdCost.setHorizontalAlignment(SwingConstants.RIGHT);

    jLabel4.setText(com.floreantpos.POSConstants.GROUP + ":");

    btnPrintToKitchen.setText(com.floreantpos.POSConstants.PRINT_TO_KITCHEN);
    btnPrintToKitchen.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    btnPrintToKitchen.setMargin(new java.awt.Insets(0, 0, 0, 0));

    btnPizzaModifier.setText("Modificação define o preço do Grupo");
    btnPizzaModifier.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    btnPizzaModifier.setMargin(new java.awt.Insets(0, 0, 0, 0));

    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel1)
                            .add(jLabel4)
                            .add(jLabel2)
                            .add(jLabel5))
                    .add(9, 9, 9)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel1Layout.createSequentialGroup()
                                    .add(btnPrintToKitchen)
                                    .addContainerGap())
                            .add(jPanel1Layout.createSequentialGroup()
                                    .add(btnPizzaModifier)
                                    .addContainerGap())
                            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jPanel1Layout.createSequentialGroup()
                                            .add(tfName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
                                            .addContainerGap())
                                    .add(jPanel1Layout.createSequentialGroup()
                                            .add(cbModifierGroup, 0, 290, Short.MAX_VALUE)
                                            .addContainerGap())
                                    .add(jPanel1Layout.createSequentialGroup()
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .add(59, 59, 59))
                                    .add(jPanel1Layout.createSequentialGroup()
                                            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                                    .add(org.jdesktop.layout.GroupLayout.LEADING, tfStdCost)
                                                    .add(org.jdesktop.layout.GroupLayout.LEADING, tfPrice, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
                                            .addContainerGap()))))
    );
    jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(tfName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel4)
                            .add(cbModifierGroup, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                      .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel2)
                            .add(tfPrice, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel5)
                            .add(tfStdCost, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(btnPrintToKitchen)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(btnPizzaModifier)
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jTabbedPane1.addTab(com.floreantpos.POSConstants.GENERAL, jPanel1);

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
    );
    layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 234, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
  }

  private javax.swing.JCheckBox btnPrintToKitchen;
  private javax.swing.JCheckBox btnPizzaModifier;
  private javax.swing.JComboBox cbModifierGroup;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private com.floreantpos.swing.TransparentPanel jPanel1;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JFormattedTextField tfName;
  private javax.swing.JFormattedTextField tfPrice;
  private javax.swing.JFormattedTextField tfStdCost;
  private DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("pt", "BR")));
  private Tax tax = new Tax();

  @Override
  public boolean save() {
    try {
      if (!updateModel()) {
        return false;
      }

      MenuModifier modifier = (MenuModifier) getBean();
      ModifierDAO dao = new ModifierDAO();
      dao.saveOrUpdate(modifier);
    } catch (Exception e) {
      MessageDialog.showError(com.floreantpos.POSConstants.SAVE_ERROR, e);
      return false;
    }
    return true;
  }

  @Override
  public void dispose() {
  }

  @Override
  protected void updateView() {
    MenuModifier modifier = (MenuModifier) getBean();

    if (modifier == null) {
      tfName.setText("");
      tfPrice.setText("0,00");
      tfStdCost.setText("0,00");
      return;
    }

    tfName.setText(modifier.getName());
    tfPrice.setValue(Application.formatNumber(Double.valueOf(modifier.getPrice())));
    tfStdCost.setValue(Application.formatNumber(Double.valueOf(modifier.getStdCost())));
    cbModifierGroup.setSelectedItem(modifier.getModifierGroup());
    btnPrintToKitchen.setSelected(modifier.isShouldPrintToKitchen());
    btnPizzaModifier.setSelected(modifier.isPizzaModifier());
  }

  @Override
  protected boolean updateModel() {
    MenuModifier modifier = (MenuModifier) getBean();

    String name = tfName.getText();
    if (POSUtil.isBlankOrNull(name)) {
      MessageDialog.showError("O Nome é Obrigatório");
      return false;
    }
    
    if (name.length() > 28) {
      MessageDialog.showError("O Nome deve conter no máximo 28 caracteres.");
      return false;      
    }
    
    modifier.setName(name);    

    if (cbModifierGroup.getSelectedItem() == null) {
      MessageDialog.showError("O Grupo é Obrigatório");
      return false;
    }

    try {
      modifier.setPrice(Double.valueOf(decimalFormat.parse(tfPrice.getValue().toString()).doubleValue()));
    } catch (ParseException ex) {
      MessageDialog.showError("Valor Inválido");
      Logger.getLogger(MenuModifierForm.class.getName()).log(Level.SEVERE, null, ex);
      return false;
    }
    try {
      modifier.setExtraPrice(Double.valueOf(decimalFormat.parse(tfPrice.getValue().toString()).doubleValue()));
    } catch (ParseException ex) {
      Logger.getLogger(MenuModifierForm.class.getName()).log(Level.SEVERE, null, ex);
      return false;
    }
    try {
      modifier.setStdCost(Double.valueOf(decimalFormat.parse(tfStdCost.getValue().toString()).doubleValue()));
    } catch (ParseException ex) {
      MessageDialog.showError("Custo Std. Inválido");
      Logger.getLogger(MenuModifierForm.class.getName()).log(Level.SEVERE, null, ex);
      return false;
    }
    
    if (modifier.getPrice() > 999999.99) {
      MessageDialog.showError("O Valor Máximo permitido é R$ 999.999,99.");
      return false;      
    }
    
    if (modifier.getPrice() <= 0) {
      MessageDialog.showError("O Valor deve ser maior que R$ 0,00.");
      return false;      
    }
    
    if (modifier.getStdCost() > 999999.99) {
      MessageDialog.showError("O Custo Std. Máximo permitido é R$ 999.999,99.");
      return false;      
    }
    
    if (modifier.getStdCost() < 0) {
      MessageDialog.showError("O Custo Std. deve ser maior ou igual a R$ 0,00.");
      return false;      
    }    
    
    modifier.setTax(tax);
    modifier.setModifierGroup((MenuModifierGroup) cbModifierGroup.getSelectedItem());
    modifier.setShouldPrintToKitchen(Boolean.valueOf(btnPrintToKitchen.isSelected()));
    modifier.setPizzaModifier(Boolean.valueOf(btnPizzaModifier.isSelected()));

    return true;
  }

  public String getDisplayText() {
    MenuModifier modifier = (MenuModifier) getBean();
    if (modifier.getId() == null) {
      return "Nova Modificação";
    }
    return "Alterar Modificação";
  }
}
